package com.damai.action.json;

import java.io.IOException;
import java.io.InputStream;

import com.citywithincity.api.IFileReader;
import com.citywithincity.api.upload.FileInfo;
import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.UploadFileInfo;
import com.citywithincity.utils.UploadUtil;
import com.damai.action.json.FileParamParser.ApiUploadFileInfo;
import com.damai.annotation.UploadFile;

public class ApiFileReader implements IFileReader {
	private int[] lengths;
	private ApiUploadFileInfo[] infos;
	private int contentLength;
	private int index;
	private InputStream inputStream;
	ApiFileReader(int[] lengths, ApiUploadFileInfo[] infos,int contentLength,InputStream inputStream){
		this.lengths = lengths;
		this.infos = infos;
		this.contentLength = contentLength;
		this.inputStream = inputStream;
	}
	
	public boolean hasNext(){
		return index < lengths.length;
	}
	
	public FileInfo next() throws IOException{
		int len = lengths[index];
		ApiUploadFileInfo info = infos[index];
		contentLength-=len;
		index++;
		String ext=info.ext;
		String name = info.name;
		//保存文件
		FileInfo fileInfo = new FileInfo();
		fileInfo.setType(info.type);
		fileInfo.setExt(ext);
		fileInfo.setName(name);
		
		if(info.type==UploadFile.UploadToFile){
			UploadFileInfo info2 = UploadUtil.getUploadFileInfo(ext) ;
			IoUtil.write(info2.getFile(), inputStream,len);
			fileInfo.setFile(info2.getFile());
			fileInfo.setPath(info2.getUri());
		}else{
			byte[] bytes = new byte[len];
			inputStream.read(bytes);
			fileInfo.setBytes(bytes);
		}
		
		
		return fileInfo;
	}

	@Override
	public void close() {
		try {
			inputStream.close();
		} catch (IOException e) {
		}
	}
}
